package usersManagement.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import usersManagement.model.User;
import usersManagement.service.UserService;
import usersManagement.util.AppLog;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;


@Named("auth")
@RequestScoped
public class AuthenticationController implements Serializable {
// ------------------------------ FIELDS ------------------------------

	private static final long serialVersionUID = 8277824266030751108L;

	@Inject
    private FacesContext facesContext;

    @Inject @AppLog
    private Logger log ;

    private String username;
    private String password;

    @Inject
    UserService userService;

// -------------------------- OTHER METHODS --------------------------

    private Subject currentUser = SecurityUtils.getSubject();

    /**
     * get username & password from Shiro PassThruAuthenticationFilter and authenticate the user
     * also set in session the full name of the subject to dislay it (subject is normally the username)
     * @return navigation
     */
    public String login() {

        log.info("Trying to login {}/{}", username, password);

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                currentUser.login(token);
                User user = userService.findByUsername(username) ;
                //currentUser.getSession().setAttribute("fullName",user.getFullName());
                //currentUser.getSession().setAttribute("organization",user.getOrganization());
              return "index.jsf?faces-redirect=true";
            } catch (UnknownAccountException uae) {
                facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "User name does not exist", null));
            } catch (IncorrectCredentialsException ice) {
                facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Password is wrong!", null));
            } catch (AuthenticationException lae) {
                facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error during Login", null));
            }
        }
        return null;
    }

    /**
     * logout & redirect
     * @return navigation
     */
    public String logout() {

        currentUser.logout();
        return "login?faces-redirect=true" ;
    }


// --------------------- GETTER / SETTER METHODS ---------------------

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
